package com.alinesno.cloud.operation.cmdb.controller.manager;

import java.io.File;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alinesno.cloud.operation.cmdb.advice.ConvertCode;
import com.alinesno.cloud.operation.cmdb.common.constants.GoodsEnum;
import com.alinesno.cloud.operation.cmdb.common.excel.PoiExcelExport;
import com.alinesno.cloud.operation.cmdb.controller.BaseController;
import com.alinesno.cloud.operation.cmdb.entity.AssertsEntity;
import com.alinesno.cloud.operation.cmdb.entity.OrderInfoEntity;
import com.alinesno.cloud.operation.cmdb.repository.AssertsRepository;
import com.alinesno.cloud.operation.cmdb.third.data.QiniuUploadTool;
import com.alinesno.cloud.operation.cmdb.web.bean.FileMeta;
import com.alinesno.cloud.operation.cmdb.web.bean.JqDatatablesPageBean;
import com.alinesno.cloud.operation.cmdb.web.bean.MachineBean;
import com.alinesno.cloud.operation.cmdb.web.bean.ResponseBean;
import com.alinesno.cloud.operation.cmdb.web.bean.ResultGenerator;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;

/**
 * 商品管理
 * 
 * @author LuoAnDong
 * @since 2018年9月9日 下午9:26:41
 */
@Controller
@RequestMapping("/manager/")
public class ManagerAssertsController extends BaseController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private AssertsRepository assertsRepository;
	
	@Autowired
	private QiniuUploadTool qiniuUploadTool ; 

	@GetMapping("/asserts_list")
	public String list(Model model) {
		createMenus(model);

		return WX_MANAGER + "asserts_list";
	}

	@GetMapping("/asserts_import_data")
	public String importData(Model model) {
		return WX_MANAGER + "asserts_import_data";
	}
	
    @RequestMapping(value="/asserts_upload_data", method = RequestMethod.POST)
    public @ResponseBody LinkedList<FileMeta> upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    	
    	LinkedList<FileMeta> files =  qiniuUploadTool.uploadLocal(request , stackFileExport);
    	FileMeta f = files.get(0) ; 
    	String filePath = f.getFilePath() ;
    	
    	logger.debug("文件保存路径:{} , 保存路径:{}" , filePath , stackFileExport);
    
    	ImportParams params = new ImportParams();
        List<AssertsEntity> result = ExcelImportUtil.importExcel(new File(filePath),AssertsEntity.class, params);
        
        for (AssertsEntity e : result) {
            logger.debug(ReflectionToStringBuilder.toString(e));
            e.setManagerName(currentManager().getId());
            e.setMasterCode(currentManager().getMasterCode());
        }
        
        assertsRepository.saveAll(result) ; 
    	return files ; 
    }

	@GetMapping("/asserts_add")
	public String goodsAdd(Model model) {

		// 列出所有母机
//		Iterable<ServerEntity> servers = budinessServerRepository.findAllByMasterCodeAndHasStatus(currentManager().getMasterCode(), BusinessStatusEnum.NORMAL.getCode(), null);
//		model.addAttribute("servers", servers);

		return WX_MANAGER + "asserts_add";
	}

	@GetMapping("/asserts_modify/{id}")
	public String goodsModify(Model model, @PathVariable("id") String id) {
		logger.debug("id = {}", id);

		AssertsEntity bean = assertsRepository.findById(id).get();
		model.addAttribute("bean", bean);

		// 列出所有母机
//		Iterable<ServerEntity> servers = budinessServerRepository.findAllByMasterCodeAndHasStatus(currentManager().getMasterCode(), BusinessStatusEnum.NORMAL.getCode(), null);
//		model.addAttribute("servers", servers);

		return WX_MANAGER + "asserts_modify";
	}

	@ResponseBody
	@GetMapping("/asserts_delete/{id}")
	public ResponseBean<String> goodsDelete(Model model, @PathVariable("id") String id) {
		logger.debug("id = {}", id);
		assertsRepository.deleteById(id);
		return ResultGenerator.genSuccessMessage("删除成功.");
	}

	/**
	 * 数据列表
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ConvertCode
	@ResponseBody
	@GetMapping("/asserts_list_data")
	public Object memberListData(Model model, JqDatatablesPageBean page, String runnerStatus) {
		return this.toPage(model, page.buildFilter(AssertsEntity.class, request), assertsRepository, page);
	}

	/**
	 * 修改上下架
	 * 
	 * @param model
	 * @return
	 */
	@ResponseBody
	@PostMapping("/asserts_sale")
	public ResponseBean<String> goodsSale(Model model, String status, String id) {
		logger.debug("商品{} , 修改状态:{}", id, status);

		AssertsEntity goods = assertsRepository.findById(id).get();
		if (goods == null) {
			return ResultGenerator.genFailMessage("商品查询为空.");
		}
		goods.setUpdateTime(new Date());
//		goods.setMachineStatus(status);

		assertsRepository.save(goods);

		return ResultGenerator.genSuccessResult(GoodsEnum.getStatus(status).getCode());
	}

	/**
	 * 保存添加
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/asserts_add_save", method = RequestMethod.POST)
	public ResponseBean<String> saveAdd(Model model,
			/* @RequestParam("file") MultipartFile file, */ AssertsEntity bean) {

		bean.setMasterCode(currentManager().getMasterCode());
		bean.setAddTime(new Date());
		bean.setUpdateTime(new Date());

		assertsRepository.save(bean);

		return ResultGenerator.genSuccessMessage("保存成功.");
	}

	/**
	 * 保存修改订单
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@PostMapping("/asserts_modify_save")
	public ResponseBean<String> saveModify(Model model, MultipartFile file, MachineBean vo, String id) {
		AssertsEntity bean = assertsRepository.findById(id).get();

		if (bean == null) {
			return ResultGenerator.genFailMessage("查询商品信息为空.");
		}

//		if (file != null) {
//			String netUrl = qiniuUploadTool.uploadFile(file);
//			if (StringUtils.isNoneBlank(netUrl)) {
//				vo.setMachinePic(netUrl);
//			}
//		}

		BeanUtils.copyProperties(vo, bean);
		logger.debug("bean = {}", ToStringBuilder.reflectionToString(bean));

		assertsRepository.save(bean);

		return ResultGenerator.genSuccessMessage("修改成功.");
	}

	/**
	 * 数据导出
	 * 
	 * @param model
	 * @param page
	 * @return
	 */
	@ResponseBody
	@PostMapping("/asserts_export")
	public ResponseBean<String> databaseExport(Model model, JqDatatablesPageBean page) {

		List<AssertsEntity> listPage = this.toExport(model, page.buildFilter(OrderInfoEntity.class, request),
				assertsRepository, page, null);
		boolean b = false;
		String saveName = null;

		if (listPage != null && listPage.size() > 0) {

			saveName = UUID.randomUUID().toString() + ".xls";
			PoiExcelExport pee = new PoiExcelExport(stackFileExport, saveName, "详情");

			String column[] = { "dbaLoginName", "dataSpaceName", "dataSpaceSize", "indexSpaceName", "indexSpaceSize",
					"spaceDesc", "managerMan", "hostname", "hostIp", "sendTime", "endTime" };
			String title[] = { "登陆名称", "数据库空间", "数据库空间大小", "索引空间", "索引空间大小", "数据库使用描述", "管理员", "主机名称", "主机IP", "开始使用时间",
					"开始使用时间" };
			int size2[] = { 15, 20, 20, 20, 20, 23, 15, 15, 15, 20, 20 };

			pee.wirteExcel(column, title, size2, listPage);
			logger.debug("list page = {}", listPage);
			b = true;
		}

		return b ? ResultGenerator.genSuccessMessage(saveName) : ResultGenerator.genFailMessage("保存失败.");
	}

}
